<template>
  <div>
    <h1> {{id? '编辑': '新建'}}物品</h1>
    <el-form label-width='100px' @submit.native.prevent='save'>
      <el-form-item label='物品名称'>
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label='物品图标'>
        <el-upload class="avatar-uploader" 
        :action="uploadUrl" 
        :show-file-list="false"
        :headers="getAuthorization()"
          :on-success="afterUpload">
          <img v-if="model.icon" :src="model.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <!-- native-type: 表示其原生类型是submit -->
        <el-button type='primary' native-type='submit'>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      model: {
        icon: ''
      },
    };
  },
  methods: {
    async save() {
      let res;
      if (this.id) {
        // id存在则证明此时是编辑保存操作 => 更新数据
        res = await this.$http.put(`rest/items/${this.id}`, this.model);
      } else {
        // 否则是新建保存操作 => 新增
        res = await this.$http.post("rest/items", this.model);
      }
      if (res.data) {
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.$router.push("/items/list");
      }
    },
    // 根据id查询分类信息
    async fetchById() {
      const res = await this.$http.get(`rest/items/${this.id}`);
      this.model = res.data;
    },
    // 图片上传完成后做的事情
    async afterUpload(res){
      this.model.icon = await res.url
      // this.$set(this.model, 'icon', res.url)
    }
  },
  created() {
    if (this.id) {
      this.fetchById();
    }
  },
};
// self.xhr.send(payload) 注释该行不会报sockio.js错误
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px!important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>